#include "constants.h";

XfMissionChapterExecute={
	private ["_chapter_succeeded"];
	diag_log "";
	diag_log "=========================================================================";
	diag_log "                             CHAPTER 1                                   ";
	diag_log "=========================================================================";
	diag_log "";
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Starting Chapter","_last_random_reinforcement","_random_reinf_diff","_reinforcement_power"];
	DM_Mission_ArtilleryVariables = [];
	DM_Mission_Chapter_CanRun = True;
	DM_Mission_Chapter_Runs = True;
	DM_Mission_Chapter_Success = 0;
	call XfMissionChapterSetup;
	_chapter_succeeded = false;
	if (!DM_Mission_Mission_CanRun) exitWith {diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Mission canceled!"];};

	_military_spot = DM_Chapter_Location;
	_military_pos = _military_spot select XF_MAP_LOCATION_CENTER;
	_military_pos_size = _military_spot select XF_MAP_LOCATION_SIZE;
	_players = call XPlayersNumber;
	_enemy_troops = 15 + _players + DM_Mission_EnemyPower * 4 + DM_Mission_EnemyCoeff * 4;
	_current_amount = 1;
	_amount_increment = 1;
	_active_enemies = 0;
	_wave_interval = 300;
	_time_dead = 600;
	switch (true) do {
		case (_players <= 5): { _amount_increment = _amount_increment + 1; _time_dead = 600;};
		case (_players <= 10): { _amount_increment = _amount_increment + 2; _time_dead = 400;};
		case (_players <= 15): { _amount_increment = _amount_increment + 2; _time_dead = 300;};
		case (_players <= 20): { _amount_increment = _amount_increment + 3; _time_dead = 200;};
		default {_amount_increment = _amount_increment + 3;_time_dead = 100;};
	};
	_current_amount = _amount_increment;
	_players_found = false;
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun AND !_players_found} do {
		if (X_MP) then {
			_players_found = false;
			{
				if (([(getPos _x), _military_pos, _military_pos_size * 3] call XfPointInCircle) && isplayer _x && alive _x) exitWith { _players_found = true; };
			}foreach playableUnits;
		} else {
			if (alive player) then { _players_found = ([(getPos player), _military_pos, _military_pos_size * 3] call XfPointInCircle); };
		};
		sleep 15;
	};
	"STR_MF_M_ALAMO_START" call XfMissionMessageToAll;
	sleep 20;
	_attacking_groups = [];
	_last_wave = 0;
	_timer = -1;
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Entering the loop",[_players,_enemy_troops,_current_amount,_amount_increment], Time];
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun} do {
		sleep 10;
		_enemy_counts = ([_military_pos,_military_pos_size,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
		
		// We check if there are alive players left in the base
		_players_found = true;
		if (X_MP) then {
			_players_found = false;
			{
				if (([(getPos _x), _military_pos, _military_pos_size * 3] call XfPointInCircle) && isplayer _x && alive _x) exitWith { _players_found = true; };
			}foreach playableUnits;
		} else {
			if (alive player) then { _players_found = ([(getPos player), _military_pos, _military_pos_size * 3] call XfPointInCircle); };
		};
		_players = call XPlayersNumber;
		_wave_interval = 240;
		switch (true) do {
			case (_players <= 5): { _wave_interval = 240 };
			case (_players <= 10): { _wave_interval = 200 };
			case (_players <= 15): { _wave_interval = 200 };
			case (_players <= 20): { _wave_interval = 120 };
			default {_wave_interval = 120;};
		};

		if (!_players_found) then {
			if (_timer <= 0) then {
				_timer = time + _time_dead;
			} else {
				if (_timer < time) then {
					DM_Mission_Chapter_CanRun = false;
					_chapter_succeeded = false;
				};
			};
		} else {
			_timer = 0;
			if (_enemy_troops > 0) then {
				_active_enemies = 0;
				{	_active_enemies = _active_enemies + count (units _x);
				} foreach _attacking_groups;
				if (count _attacking_groups < 1 || ((_last_wave + _wave_interval) < time) || _active_enemies < 6) then {
					diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Attacking Wave",[count _attacking_groups, _last_wave, _wave_interval,_current_amount,_enemy_troops, _active_enemies], Time];
					_last_wave = time;
					if (_current_amount > _enemy_troops) then { _current_amount = _enemy_troops; };
					_enemy_troops = _enemy_troops - _current_amount;
					
					// _unique_id = [d_enemy_side,[_military_pos,_military_pos_size],"MEN",_current_amount,-1,[],0] call XfMissionCallReinforcement;
					[d_enemy_side,_military_pos,_military_pos_size * 0.7,_current_amount,floor(random(5)),[]] call XfMissionReinforcementMen;
					_attacking_groups = d_c_attacking_grps;
					diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Attacking Groups",_attacking_groups, Time];
					
					_current_amount = _current_amount + _amount_increment;
				};
			};
			_active_enemies = 0;
			{	_active_enemies = _active_enemies + count (units _x);
			} foreach _attacking_groups;
		};	
		if (_active_enemies <= 5 && _enemy_troops <= 0) then {
			DM_Mission_Chapter_CanRun = false;
			_chapter_succeeded = true;
			["DefendTheCamp","", "","",[],"Succeeded"] call XfMissionTask;
		};
	};
	sleep 15;
	if (DM_Mission_Mission_CanRun) then {
		if (_chapter_succeeded) then {
			call XfMissionChapterSuccess;
		} else {
			call XfMissionChapterFailure;
		};
	} else {
		diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Mission canceled!"];
	};
	
	_players_found = true;
	_enemy_count = 100;
	While {DM_Mission_Mission_CanRun && _enemy_count > 3 && _players_found} do {
		sleep 5;
		if (X_MP) then {
			_players_found = false;
			{
				if (([(getPos _x), _military_pos, _military_pos_size * 3] call XfPointInCircle) && isplayer _x) exitWith { _players_found = true; };
			}foreach playableUnits;
		} else {
			_players_found = ([(getPos player), _military_pos, _military_pos_size * 3] call XfPointInCircle);
		};
		_enemy_count = (([_military_pos,600,d_enemy_side] call XfMissionGetZoneSideCount) select 0);
		if (d_mission_debug_messages) then { diag_log Format["(%1)[%2]: %3: %4: player:%5  enemies:%6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Chapter End Check",_players_found,_enemy_count]; };
	};
	// Just in case a reinforcement is already on the way.
	call XfMissionCancelReinforcement;
	call XfMissionChapterCleanUp;
	DM_Mission_Chapter_Runs = False;
};

XfMissionChapterSetup={
	private ["_military_site","_military_pos","_military_pos_size","_troops_power","_troops_coeff","_grpSpecOps","_i"];
	diag_log Format["(%1)[%2]: %3; %4 %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Starting Initialization:",DM_Mission_Name];
	
	_military_site = [];
	_military_pos = [];
	_military_pos_size = 150;
	_i_tries = 20;
	while { ((count _military_site) <= 0) && (_i_tries > 0) && DM_Mission_Mission_CanRun && DM_Mission_Chapter_CanRun } do {
		_military_site = [[XF_MAP_LOCATION_TYPE_MILITARY]] call XfMissionGetRandomSpot;
		// diag_log Format["(%1)[%2]: %3: %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Picked up", _military_site];
		if ( count _military_site > 0 ) then {
			_military_pos = _military_site select XF_MAP_LOCATION_CENTER;
			_military_pos_size = _military_site select XF_MAP_LOCATION_SIZE;
		};
	};
	if ((count _military_site) <= 0) exitWith {"STR_MF_RANDOMSITEFAILED" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	_military_pos_name = _military_site select XF_MAP_LOCATION_DISPLAYNAME;
	
	DM_Chapter_Location = _military_site;
	DM_Chapter_Position = _military_pos;
	
	// This indicates where the mission takes place
	[_military_pos,_military_pos_size,_military_pos_name] call XfMissionCurrentPosition;
	
	_teleporter = [_military_pos] call XfMissionRandomStartTeleporter;
	// If no spot found, we get back an empty position.
	if (count (_teleporter select 0) > 0) then {
		[false,["chapter1_start_position",(_teleporter select 0), "ICON", "ColorBlue", [1,1],"",(_teleporter select 1),"hd_start","",1]] call XfMissionMarker;
	};
	_radius_box = (_military_pos_size / 1.7);
	if (_radius_box > 50) then { _radius_box = 50 };
	_random_point = [_military_pos, _radius_box, 7] call XfGetRanPointCircleBig;
	if (count _random_point < 3) then { _random_point = [_military_pos, (_military_pos_size / 1.5)] call XfGetRanPointCircle; };
	if (count _random_point < 3) exitWith {["STR_MF_RANDOMOBJECTFAILED","Ammo Box"] call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	[_random_point, d_own_side, "USOrdnanceBox"] call XfMissionCreateBox;
	// [false,["chapter1_box_position",_random_point, "ICON", "ColorBlack", [0.6,0.6],"STR_MF_AMMOBOX",0,"Marker","",0.6]] call XfMissionMarker;

	[false,["chapter1_military_zone", _military_pos, "ELLIPSE", "ColorRed", [_military_pos_size,_military_pos_size],"",0,"","BDiagonal",0.5]] call XfMissionMarker;
	[false,["chapter1_military_position",_military_pos, "ICON", "ColorRed", [0.8,0.8],_military_pos_name,0,"hd_flag","",0.6]] call XfMissionMarker;
	
	["DefendTheCamp","STR_MF_M_ALAMO_TASK_DEFEND", ["STR_MF_M_ALAMO_TASK_DEFEND_DESC",_military_pos_name],"",[],"Created"] call XfMissionTask;
};

XfMissionChapterSuccess={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSuccess","Starting"];
	"STR_MF_M_ALAMO_SUCCESS" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = 1;
};

XfMissionChapterFailure={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterFailure","Starting"];
	"STR_MF_MISSIONFAILURE1" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = -1;
};

// Self-explanatory
XfMissionChapterCleanUp={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterCleanUp","Starting"];
	// Giving an empty position places the teleporter back to the hangar, closing the hangar.
	[[],0] call XfMissionPlaceStartTeleporter;
	[] call XfMissionCleanMarkers;
	[] call XfMissionCleanTriggers;
	[] call XfMissionCleanTasks;
};

DM_Mission_Chapter_Compiled = true;